<script setup>
import { popupPowerBank } from '@/api/my';

//响应式变量
const popupStatuText = ref('充电宝准备中...');
const fail = ref(false); // 显示失败图标
const success = ref(false); // 是否显示成功图片
const value = ref(0); // 进度条
let interval = null; // 进度条对象
const hidden = ref(true);
const orderId = ref(0);

// 停止进度条
const stopProgress = () => {
  if (interval) {
    clearInterval(interval);
    interval = null;
  }
};

// 开始进度条
const startProgress = () => {
  interval = setInterval(() => {
    value.value += 3;
    if (value.value >= 99) {
      stopProgress();
    }
  }, 50);
};

// 完成进度条
const completeProgress = () => {
  value.value = 100;
  success.value = true;
  stopProgress();
};

// 失败
const failProgress = (message) => {
  popupStatuText.value = message;
  value.value = 0;
  fail.value = true;
  stopProgress();
};

// 弹出充电宝
const popup = async (deviceId) => {
  try {
    let _deviceId = deviceId || uni.getStorageSync('deviceId');
    const couponRecoreId = uni.getStorageSync('couponRecoreId') || 0;
    console.log('couponRecoreId', couponRecoreId);
    const res = await popupPowerBank(_deviceId, couponRecoreId);
    console.log('弹出充电宝--------->popupPowerBank', res);
    if (res.code === 200) {
      uni.removeStorageSync('couponRecoreId');
      hidden.value = false;
      orderId.value = res.data;
      completeProgress();
      uni.reLaunch({
        url: `/pages/popupSuccess/popupSuccess?id=${orderId.value}&check=true`
      });
    } else {
      failProgress(res.message || '弹出失败');
    }
  } catch (error) {
    console.error('弹出充电宝错误:', error);
    failProgress('网络错误，请稍后重试');
  }
};

/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  console.log('options', options);
  startProgress();
  popup(options.id);
});

/**
 * 生命周期函数--页面销毁
 */
onUnload(() => {
  stopProgress();
});
</script>

<template>
  <view class="paybox">
    <image class="pay" src="@/static/images/icon_popup.png"></image>
  </view>
  <view class="text">{{ popupStatuText }}({{ value }}%)</view>
</template>

<style lang="scss" scoped>
page {
  background-color: #fff;
}
.paybox {
  display: flex;
  justify-content: center;
  margin-top: 230rpx;
  width: 750rpx;
  height: 322rpx;
  .pay {
    width: 350rpx;
    height: 350rpx;
  }
}
.text {
  margin-top: 20rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #212121;
  text-align: center;
}
</style>
